package com.wing.storage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.purchase.dao.WarehouseShelfSpaceDao;
import com.wing.purchase.model.entity.WarehouseShelfSpace;
import com.wing.storage.dao.ProductInventoryDao;
import com.wing.storage.dao.ProductInventoryDetailDao;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.model.entity.ProductInventoryDetail;
import com.wing.storage.model.entity.ProductInventoryRecord;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 产品库存明细-ServiceImpl
 *
 * @author xiayang
 */
@Service
@Slf4j
public class ProductInventoryDetailServiceImpl extends ServiceImpl<ProductInventoryDetailDao, ProductInventoryDetail> implements ProductInventoryDetailService {

    @Resource
    ProductInventoryService productInventoryService;

    @Resource
    ProductInventoryRecordService productInventoryRecordService;

    @Resource
    ProductDetailService productDetailService;

    @Autowired
    WarehouseShelfSpaceDao warehouseShelfSpaceDao;

    @Override
    public Page<ProductInventoryDetail> pageList(Page page, Map<String, Object> params) {
        List<ProductInventoryDetail> list = new ArrayList<>();
        //TODO 未知其他界面是否调用 暂时用户暂时不删除
        if(params.get("productDetailId")!=null && params.get("warehouseId")!=null){
            //入库作业时候使用
             list = baseMapper.pageList2(page, params);
        }else{
            list = baseMapper.list(page, params);
        }
       page.setRecords(list);
        return page;
    }

    @Override
    public void productInStorage(ProductInventoryDetail productInventoryDetail) {

        try {
            //物料信息2
            ProductDetail productDetail = productDetailService.getById(productInventoryDetail.getProductDetailId());
            //判断采购入库产品是否存在库存
            QueryWrapper<ProductInventory> inventoryQueryWrapper = new QueryWrapper<ProductInventory>();
            inventoryQueryWrapper.eq("product_detail_id", productInventoryDetail.getProductDetailId());
            ProductInventory productInventory = productInventoryService.getOne(inventoryQueryWrapper);
            //采购入库产品库存不存在则新增库存
            if (productInventory == null) {
                //新增库存
                productInventory = new ProductInventory();
                productInventory.setProductDetailId(productInventoryDetail.getProductDetailId());
                productInventory.setQuantity(productInventoryDetail.getQuantity());
                productInventoryService.save(productInventory);
                //新增库存明细
                productInventoryDetail.setProductInventoryId(productInventory.getId());
                productInventoryDetail.setCreator(JwtUtils.getLoginUserId());
                productInventoryDetail.setCreateTime(LocalDateTime.now());
                productInventoryDetail.setCreatorName(JwtUtils.getLoginUsername());
                baseMapper.insert(productInventoryDetail);
                //新增库存记录
                ProductInventoryRecord productInventoryRecord = new ProductInventoryRecord();
                productInventoryRecord.setCurrentCostPrice(productDetail.getCurrentCostPrice());
                productInventoryRecord.setInoutType(productInventoryDetail.getInoutType());
                productInventoryRecord.setInoutWorkJob(productInventoryDetail.getInoutWorkJob());
                productInventoryRecord.setProductInventoryDetailId(productInventoryDetail.getId());
                productInventoryRecord.setQuantityCurrent(BigDecimal.ZERO);
                productInventoryRecord.setQuantity(productInventoryDetail.getQuantity());
                productInventoryRecord.setQuantityAfter(productInventoryDetail.getQuantity());
                productInventoryRecordService.save(productInventoryRecord);
            } else {
                //更新库存
                productInventory.setQuantity(productInventory.getQuantity().add(productInventoryDetail.getQuantity()));
                productInventoryService.updateById(productInventory);


                //更新库存明细
                QueryWrapper<ProductInventoryDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.eq("product_detail_id", productInventoryDetail.getProductDetailId());
                detailQueryWrapper.eq("product_inventory_id", productInventory.getId());
                detailQueryWrapper.eq("warehouse_type_id", productInventoryDetail.getWarehouseTypeId());
                detailQueryWrapper.eq("warehouse_id", productInventoryDetail.getWarehouseId());
                detailQueryWrapper.eq("warehouse_area_id", productInventoryDetail.getWarehouseAreaId());
                /*   detailQueryWrapper.eq("warehouse_shelf_id", productInventoryDetail.getWarehouseShelfId());*/
                detailQueryWrapper.eq("warehouse_shelf_space_id", productInventoryDetail.getWarehouseShelfSpaceId());
                if (productInventoryDetail.getPalletBoxId() != null) {
                    detailQueryWrapper.eq("pallet_box_id", productInventoryDetail.getPalletBoxId());
                }
                WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceDao.selectById(productInventoryDetail.getWarehouseShelfSpaceId());
                if(warehouseShelfSpace!=null){
                       detailQueryWrapper.eq("warehouse_shelf_id", warehouseShelfSpace.getShelfId());
                }

                ProductInventoryDetail productInventoryDetail0 = baseMapper.selectOne(detailQueryWrapper);
                if (productInventoryDetail0 != null) {
                    productInventoryDetail0.setQuantity(productInventoryDetail0.getQuantity().add(productInventoryDetail.getQuantity()));
                    baseMapper.updateById(productInventoryDetail0);
                    productInventoryDetail.setId(productInventoryDetail0.getId());
                } else {
                    productInventoryDetail.setProductInventoryId(productInventory.getId());
                    productInventoryDetail.setCreator(JwtUtils.getLoginUserId());
                    productInventoryDetail.setCreateTime(LocalDateTime.now());
                    productInventoryDetail.setCreatorName(JwtUtils.getLoginUsername());
                    baseMapper.insert(productInventoryDetail);
                }
                //新增库存记录
                ProductInventoryRecord productInventoryRecord = new ProductInventoryRecord();
                productInventoryRecord.setCurrentCostPrice(productDetail.getCurrentCostPrice());
                productInventoryRecord.setInoutType(productInventoryDetail.getInoutType());
                productInventoryRecord.setInoutWorkJob(productInventoryDetail.getInoutWorkJob());
                productInventoryRecord.setProductInventoryDetailId(productInventoryDetail.getId());
                productInventoryRecord.setQuantityCurrent(productInventory.getQuantity());
                productInventoryRecord.setQuantity(productInventoryDetail.getQuantity());
                productInventoryRecord.setQuantityAfter(productInventory.getQuantity().add(productInventoryDetail.getQuantity()));
                productInventoryRecordService.save(productInventoryRecord);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.info("采购入库-库存明细异常：" + e);
        }

    }

    @Override
    public void productOutStorage(ProductInventoryDetail productInventoryDetail) {
        //物料信息
        ProductDetail productDetail = productDetailService.getById(productInventoryDetail.getProductDetailId());
        //判断采购入库产品是否存在库存
        QueryWrapper<ProductInventory> inventoryQueryWrapper = new QueryWrapper<ProductInventory>();
        inventoryQueryWrapper.eq("product_detail_id", productInventoryDetail.getProductDetailId());
        ProductInventory productInventory = productInventoryService.getOne(inventoryQueryWrapper);
        if (productInventory == null) {
            throw new BusinessException(300, "出库物料不存在!");
        }
        //更新库存
        productInventory.setQuantity(productInventory.getQuantity().subtract(productInventoryDetail.getQuantity()));
        productInventory.setUpdateTime(LocalDateTime.now());
        productInventoryService.updateById(productInventory);
        //更新库存明细
        QueryWrapper<ProductInventoryDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("product_detail_id", productInventoryDetail.getProductDetailId());
        detailQueryWrapper.eq("product_inventory_id", productInventory.getId());
        if (productInventoryDetail.getWarehouseTypeId() != null) {
            detailQueryWrapper.eq("warehouse_type_id", productInventoryDetail.getWarehouseTypeId());
        }
        detailQueryWrapper.eq("warehouse_id", productInventoryDetail.getWarehouseId());
        if (productInventoryDetail.getWarehouseAreaId() != null) {
            detailQueryWrapper.eq("warehouse_area_id", productInventoryDetail.getWarehouseAreaId());
        }
  /*      if (productInventoryDetail.getWarehouseShelfId() != null) {
            detailQueryWrapper.eq("warehouse_shelf_id", productInventoryDetail.getWarehouseShelfId());
        }*/
        detailQueryWrapper.eq("warehouse_shelf_space_id", productInventoryDetail.getWarehouseShelfSpaceId());
     /*   if (productInventoryDetail.getPalletBoxId() != null) {
            detailQueryWrapper.eq("pallet_box_id", productInventoryDetail.getPalletBoxId());
        }else{
            detailQueryWrapper.isNull("pallet_box_id");
        }*/
        if (productInventoryDetail.getPalletBoxId() != null) {
            detailQueryWrapper.eq("pallet_box_id", productInventoryDetail.getPalletBoxId());
        }



       /* ProductInventoryDetail productInventoryDetail0 = baseMapper.selectOne(detailQueryWrapper);
        if (productInventoryDetail0 != null) {
            if (productInventoryDetail.getQuantity().compareTo(productInventoryDetail0.getQuantity()) == 1) {
                throw new BusinessException(300, "出库库位/料箱物料不足，无法出库!");
            }
            productInventoryDetail0.setQuantity(productInventoryDetail0.getQuantity().subtract(productInventoryDetail.getQuantity()));
            productInventoryDetail0.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(productInventoryDetail0);
        } else {
            throw new BusinessException(300, "出库库位/料箱物料不存在");

        }*/

        List<ProductInventoryDetail> productInventoryDetail02 = baseMapper.selectList(detailQueryWrapper);
        // ProductInventoryDetail productInventoryDetail0 = productInventoryDetailDao.selectOne(detailQueryWrapper);
        if (productInventoryDetail02 != null && productInventoryDetail02.size()>0) {
            BigDecimal totalNum = productInventoryDetail02.stream()
                    .map(ProductInventoryDetail::getQuantity) // 获取每个 ProductInventoryDetail 对象的 num 字段
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用 reduce 方法进行求和，初始值为 BigDecimal.ZERO
            if (productInventoryDetail.getQuantity().compareTo(totalNum) == 1) {
                throw new BusinessException(300, "出库库位/料箱物料不足，无法出库!");
            }
            productInventoryDetail02.get(0).setQuantity(productInventoryDetail02.get(0).getQuantity().subtract(productInventoryDetail.getQuantity()));
            productInventoryDetail02.get(0).setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(productInventoryDetail02.get(0));
        }else {
            throw new BusinessException(300, "出库库位/料箱物料不存在");
        }

        //新增库存记录
        ProductInventoryRecord productInventoryRecord = new ProductInventoryRecord();
        productInventoryRecord.setCurrentCostPrice(productDetail.getCurrentCostPrice());
        productInventoryRecord.setInoutType(productInventoryDetail.getInoutType());
        productInventoryRecord.setInoutWorkJob(productInventoryDetail.getInoutWorkJob());
        productInventoryRecord.setProductInventoryDetailId(productInventoryDetail02.get(0).getId());
        productInventoryRecord.setQuantityCurrent(productInventory.getQuantity());
        productInventoryRecord.setQuantity(productInventoryDetail.getQuantity());
        productInventoryRecord.setQuantityAfter(productInventory.getQuantity().subtract(productInventoryDetail.getQuantity()));
        productInventoryRecordService.save(productInventoryRecord);
    }

    @Override
    public ProductInventoryDetail get(Long productInventoryDetailId) {
        return baseMapper.get(productInventoryDetailId);
    }
}
